import chatListStore from "@/store/module/chatList";
import indexedDBStore from "@/store/module/indexedDB";

/**
 * 删除数据
 */
export function deleteDB(db: any, storeName: any, id: any) {
  const request = db
    .transaction([storeName], "readwrite")
    .objectStore(storeName)
    .delete(id);

  return new Promise((resolve) => {
    request.onsuccess = function (ev: any) {
      resolve(ev);
    };

    request.onerror = function (ev: any) {
      resolve(ev);
    };
  });
}

/**
 * 新增数据
 */
export function addData(db: any, storeName: any, data: any) {
  if (data.type === "notice") return;
  return new Promise((resolve, reject) => {
    const request = db
      .transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式（"只读"或"读写"）
      .objectStore(storeName) // 仓库对象
      .add(data);

    request.onsuccess = function (event: any) {
      resolve(event);
    };

    request.onerror = function (event: any) {
      reject(event);
      throw new Error(event.target.error);
    };
  });
}
/**
 * @method 准确条件查询本地数据库单个数据
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryIndex  需要查询的索引名
 * @param queryIndexValue  对应索引名的值
 * @returns
 */
export function queryIndexDB(
  db: any,
  tableName: any,
  queryIndex: any,
  queryIndexValue: any
) {
  return new Promise((resolve, reject) => {
    var tx = db.transaction([tableName]);
    let store = tx.objectStore(tableName);
    var request = store
      .index(queryIndex) // 索引对象
      .openCursor(IDBKeyRange.only(queryIndexValue), "prev"); // 指针对象(倒序搜索)
    request.onsuccess = function (e: any) {
      if (e) {
        resolve(e);
      } else {
        reject(console.log("未查询到任何数据"));
      }
    };
  });
}
export function initIndexDB(dbName: any) {
  return new Promise((resolve, reject) => {
    let request = indexedDB.open(dbName);
    // err
    request.onerror = () => {
      reject("数据库打开/创建报错");
    };
    // success
    request.onsuccess = (event: any) => {
      resolve(event.target.result);
    };
    request.onupgradeneeded = function (event: any) {
      let db = event.target.result;
      console.log("数据库升级");
      let objectStoreMessage, objectStoreChatList;
      if (!db.objectStoreNames.contains("messages")) {
        objectStoreMessage = db.createObjectStore("messages", {
          keyPath: "id",
          autoIncrement: true,
        });
      } else {
        objectStoreMessage = event.target.transaction.objectStore("messages");
      }
      if (!db.objectStoreNames.contains("chatList")) {
        objectStoreChatList = db.createObjectStore("chatList", {
          keyPath: "id",
          autoIncrement: true,
        });
      } else {
        objectStoreChatList = event.target.transaction.objectStore("chatList");
      }
      objectStoreChatList.createIndex("id", "id", { unique: true });
      objectStoreChatList.createIndex("chatId", "chatId", { unique: false });
      objectStoreChatList.createIndex("chatAvatar", "chatAvatar", {
        unique: false,
      });
      objectStoreChatList.createIndex("chatName", "chatName", {
        unique: false,
      });
      objectStoreChatList.createIndex("toId", "toId", { unique: false });
      objectStoreChatList.createIndex("belongToId", "belongToId", {
        unique: false,
      });

      objectStoreMessage.createIndex("id", "id", { unique: true });
      objectStoreMessage.createIndex("chatId", "chatId", { unique: false });
      objectStoreMessage.createIndex("type", "type", { unique: false });
      objectStoreMessage.createIndex("from", "from", { unique: false });
      objectStoreMessage.createIndex("to", "to", { unique: false });
      objectStoreMessage.createIndex("msg", "msg", { unique: false });
      objectStoreMessage.createIndex("fileName", "fileName", { unique: false });
      objectStoreMessage.createIndex("url", "url", { unique: false });
      objectStoreMessage.createIndex("timeStamp", "timeStamp", {
        unique: false,
      });
    };
  });
}
export function queryBoundIndexDB(data: any) {
  return new Promise((resolve, reject) => {
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.queryIndex) // 索引对象
      .openCursor(
        IDBKeyRange.bound(data.queryIndexValueStart, data.queryIndexValueEnd)
      );
    request.onsuccess = function (e: any) {
      if (e) {
        resolve(e);
      } else {
        reject(console.log("未查询到任何数据"));
      }
    };
  });
}

/**
 * @method 根据条件查询本地数据库符合条件的全部数据（不分页）
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryIndex  需要查询的索引名
 * @param queryIndexValue  对应索引名的值
 * @returns
 */
export function queryIndexDBAll(data: any) {
  return new Promise((resolve, reject) => {
    let list: any = [];
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.queryIndex) // 索引对象
      .openCursor(IDBKeyRange.only(data.queryIndexValue), "prev"); // 指针对象(倒序搜索)
    request.onsuccess = function (e: any) {
      var cursor = e.target.result;
      if (cursor) {
        list.push(cursor.value);
        cursor.continue();
      } else {
        resolve(list);
      }
    };
    request.onerror = function (err: any) {
      reject(err);
    };
  });
}

/**
 * @method 分页查询本地数据库
 * @param page 查询的页码
 * @param pageSize  每页查询的数量
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryIndex  需要查询的索引名
 * @param queryIndexValue  对应索引名的值
 * @returns
 */
export function queryIndexDBByPage(data: any) {
  return new Promise((resolve, reject) => {
    let page = data.page;
    let pageSize = data.pageSize;
    let list: any = [];
    let counter = 0; // 计数器
    let advanced = true; // 是否跳过多少条查询
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.queryIndex) // 索引对象
      .openCursor(IDBKeyRange.only(data.queryIndexValue), "prev"); // 指针对象(倒序搜索)
    request.onsuccess = function (e: any) {
      var cursor = e.target.result;
      if (page > 1 && advanced) {
        advanced = false;
        cursor.advance((page - 1) * pageSize); // 跳过多少条
        return;
      }
      if (cursor) {
        list.push(cursor.value);
        counter++;
        if (counter < pageSize) {
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          cursor = null;
          resolve(list);
        }
      } else {
        resolve(list);
      }
    };
    request.onerror = function (err: any) {
      reject(err);
    };
  });
}

/**
 * @method 本地数据库模糊匹配分页查询
 * @param page 查询的页码
 * @param pageSize  每页查询的数量
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryKey  需要模糊查询的条件
 * @param key  模糊匹配的关键字
 * @returns
 */
export function queryIndexDBVagueByPage(data: any) {
  return new Promise((resolve, reject) => {
    let page = data.page;
    let pageSize = data.pageSize;
    let list: any = [];
    let counter = 0; // 计数器
    let advanced = true; // 是否跳过多少条查询
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store.openCursor(null, "prev");
    request.onsuccess = function (e: any) {
      var cursor = e.target.result;
      if (page > 1 && advanced) {
        advanced = false;
        cursor.advance((page - 1) * pageSize); // 跳过多少条
        return;
      }
      if (cursor) {
        if (
          cursor.value[data.queryKey] &&
          cursor.value[data.queryKey].indexOf(data.key) != -1
        ) {
          list.push(cursor.value);
          counter++;
        }
        if (counter < pageSize) {
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          cursor = null;
          resolve(list);
        }
      } else {
        resolve(list);
      }
    };
    request.onerror = function (err: any) {
      reject(err);
    };
  });
}

/**
 * @method 分页复合查询本地数据库
 * @param page 查询的页码
 * @param pageSize  每页查询的数量
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param compositeQueryIndex  需要查询的复合索引名
 * @param IndexValueOneStart  对应的第一个索引名的开始值
 * @param IndexValueOneEnd  对应的第一个索引名的结束值
 * @param IndexValueTwoStart  对应的第二个索引名的开始值
 * @param IndexValueTwoEnd  对应的第二个索引名的结束值
 * @returns
 */
export function compositeQueryIndexDBByPage(data: any) {
  return new Promise((resolve, reject) => {
    let page = data.page;
    let pageSize = data.pageSize;
    let list: any = [];
    let counter = 0; // 计数器
    let advanced = true; // 是否跳过多少条查询
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.compositeQueryIndex) // 索引对象
      .openCursor(
        IDBKeyRange.bound(
          [data.IndexValueOneStart, data.IndexValueTwoStart],
          [data.IndexValueOneEnd, data.IndexValueTwoEnd]
        ),
        "prev"
      );
    request.onsuccess = function (e: any) {
      var cursor = e.target.result;
      if (page > 1 && advanced) {
        advanced = false;
        cursor.advance((page - 1) * pageSize); // 跳过多少条
        return;
      }
      if (cursor) {
        list.push(cursor.value);
        counter++;
        if (counter < pageSize) {
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          cursor = null;
          resolve(list);
        }
      } else {
        resolve(list);
      }
    };
    request.onerror = function (err: any) {
      reject(err);
    };
  });
}

/**
 * @method 查询单个复合索引查询
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param compositeQueryIndex  需要查询的复合索引名
 * @param IndexValueOne  对应的第一个索引名的开始值
 * @param IndexValueTwo  对应的第二个索引名的开始值
 * @returns
 */
export function compositeQuerySingleIndexDB(data: any) {
  return new Promise((resolve, reject) => {
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.compositeQueryIndex) // 索引对象
      .openCursor([data.IndexValueOne, data.IndexValueTwo]);
    request.onsuccess = function (e: any) {
      var cursor = e.target.result;
      resolve(cursor);
    };
    request.onerror = function (err: any) {
      reject(err);
    };
  });
}

/**
 * @method 数组中对象去重
 * @param arr  需要去重的数组
 * @param key  需要判断的属性去重
 * @returns
 */
export function duplicateRemoval(arr: any, key: any) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i][key] == arr[j][key]) {
        arr.splice(j, 1);
        j--;
      }
    }
  }
}

/**
 * @method 触底加载下一页
 * @param element  需要监听滚动条位置的元素
 * @returns
 */
export function observeScroll(element: any) {
  let isBottom = false;
  element.addEventListener("scroll", () => {
    const scrollTop = element.scrollTop;
    const windowHeight = element.clientHeight;
    const scrollHeight = element.scrollHeight;
    if (scrollTop + windowHeight >= scrollHeight - 20) {
      isBottom = true;
    }
  });
}

/**
 * @method 根据某个条件对数组进行排序
 * @param arr   需要排序的数组
 * @param key   按某个条件排序
 * @param type  0为从小到大排序，1则相反
 * @returns
 */
export function arrSort(arr: any, key: any, type: any) {
  if (type == 0) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i][key] > arr[j][key]) {
          let template;
          template = arr[i];
          arr[i] = arr[j];
          arr[j] = template;
        }
      }
    }
  } else {
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i][key] < arr[j][key]) {
          let template;
          template = arr[i];
          arr[i] = arr[j];
          arr[j] = template;
        }
      }
    }
  }
}

/**
 * @method 获取时间格式化
 * @param  time   需要格式化的时间
 * @param  separator   年月日格式化后按某个符号分割
 * @returns
 */
export function timeFormat(time: any, separator: any) {
  let date = new Date(time);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  if (separator == undefined) {
    return `${year}/${month}/${day} ${hour.toString().padStart(2, "0")}:${minute
      .toString()
      .padStart(2, "0")}`;
  } else {
    return (
      year +
      separator +
      month +
      separator +
      day +
      " " +
      hour +
      ":" +
      minute +
      ":" +
      second
    );
  }
}

// //防抖函数高阶用法
// export function antiShake(func:any, timeout = 2000, immediately:any) {
//   let timeId:any = null
//   return function (...args:any) {
//     clearTimeout(timeId)
//     if (immediately) {
//       let firstRun = !timeId
//       timeId = setTimeout(() => {
//         timeId = null
//       }, timeout);
//       if (firstRun) {
//         func.apply(this, args)
//       }
//     } else {
//       timeId = setTimeout(() => {
//         func.apply(this, args)
//       }, timeout);
//     }
//   }
// }

//获取当前时间
export function getDate(time: any) {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}/${month}/${day} ${hour.toString().padStart(2, "0")}:${minute
    .toString()
    .padStart(2, "0")}`;
}

// 在用户退出登录后保存已有聊天列表

export function saveChatListDataInDB() {
  let db = indexedDBStore();
  let chatList = chatListStore();
  console.log(chatList.chatList);
}
